//
//  CheckVersionAlearView.m
//  Calculated
//
//  Created by 张庆勇 on 2018/5/21.
//  Copyright © 2018年 张庆勇. All rights reserved.
//

#import "CheckVersionAlearView.h"
#import "SC_ActionSheet.h"
#define MainScreenRect [UIScreen mainScreen].bounds
@interface CheckVersionAlearView()
@property (nonatomic,strong)UIView   *bgView;
@property (nonatomic,strong)UIImageView  *imageView;
@property (nonatomic,strong)UILabel  *titleLable;
@property (nonatomic,strong)UILabel  *measageLable;
@property (nonatomic,strong)UIButton  *okButton;
@property (nonatomic,strong)UIButton  *cancelButton;
@property (nonatomic,strong)NSString  *titleStr;
@property (nonatomic,strong)NSString  *measage;
@property (nonatomic,assign)NSInteger  state;
@property (nonatomic,strong)NSString  *canceltext;
@property (nonatomic,strong)NSString  *confirmtext;
@property (nonatomic,strong)UIButton  *QcancelButton;
@property (nonatomic,strong)UIImageView *QimageView;
@end
@implementation CheckVersionAlearView

- (instancetype)initWithmessage:(NSString *)message
                       titleStr:(NSString *)titleStr
                        openUrl:(NSString *)url
                        confirm:(NSString *)confirm
                         cancel:(NSString *)cancel
                          state:(NSInteger )state
                  RechargeBlock:(RechargeBlock)block
{
    
    if (self=[super init])
    {
        self.frame=MainScreenRect;
        self.backgroundColor=[UIColor colorWithWhite:.0 alpha:.6];
        self.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismiss)];
        [self addGestureRecognizer:tap];
        _measage = message;
        _state = state;
        _canceltext = cancel;
        _confirmtext = confirm;
        _titleStr = titleStr;
        [self addSubview:self.bgView];
        
        
        if (state ==1 )
        {
            [_bgView addSubview:self.imageView];
            [_bgView addSubview:self.titleLable];
            [_bgView addSubview:self.measageLable];
            [_bgView addSubview:self.okButton];
            _okButton.frame = CGRectMake(20 , _bgView.height - RealValue_W(74 +40), _bgView.width - 40, RealValue_W(74));
            _okButton.backgroundColor = TABTITLECOLOR;
            [_okButton setTitleColor:WHITECOLOR forState:UIControlStateNormal];
            _okButton.layer.masksToBounds     =YES;
            _okButton.layer.cornerRadius      =2;
            
        }else if (state ==2)
        {
            [_bgView addSubview:self.imageView];
            [_bgView addSubview:self.titleLable];
            [_bgView addSubview:self.measageLable];
            [_bgView addSubview:self.okButton];
            [_bgView addSubview:self.cancelButton];
            
            UIBezierPath * H_bezierPath = [UIBezierPath bezierPath];
            [H_bezierPath moveToPoint:CGPointMake(0 , _bgView.height - RealValue_W(97))];
            [H_bezierPath addLineToPoint:CGPointMake(UIScreenWidth , _bgView.height - RealValue_W(97))];
            CAShapeLayer * H_shapeLayer = [CAShapeLayer layer];
            H_shapeLayer.strokeColor = CELLCOLOR.CGColor;
            H_shapeLayer.fillColor  = [UIColor clearColor].CGColor;
            H_shapeLayer.path = H_bezierPath.CGPath;
            H_shapeLayer.lineWidth = 0.5f;
            [_bgView.layer addSublayer:H_shapeLayer];
            
            
            UIBezierPath * W_bezierPath = [UIBezierPath bezierPath];
            [W_bezierPath moveToPoint:CGPointMake(_bgView.width/2 , _bgView.height - RealValue_W(97))];
            [W_bezierPath addLineToPoint:CGPointMake(_bgView.width/2 , _bgView.height)];
            CAShapeLayer * W_shapeLayer = [CAShapeLayer layer];
            W_shapeLayer.strokeColor = CELLCOLOR.CGColor;
            W_shapeLayer.fillColor  = [UIColor clearColor].CGColor;
            W_shapeLayer.path = W_bezierPath.CGPath;
            W_shapeLayer.lineWidth = 0.5f;
            [_bgView.layer addSublayer:W_shapeLayer];
            
        }else if (state==3) {
            [_bgView addSubview:self.imageView];
            [_bgView addSubview:self.titleLable];
            [_bgView addSubview:self.measageLable];
            [_bgView addSubview:self.cancelButton];
            _cancelButton.frame = CGRectMake(20 , _bgView.height - RealValue_W(74 +40), _bgView.width - 40, RealValue_W(74));
            _cancelButton.backgroundColor = TABTITLECOLOR;
            [_cancelButton setTitleColor:WHITECOLOR forState:UIControlStateNormal];
            _cancelButton.layer.masksToBounds     =YES;
            _cancelButton.layer.cornerRadius      =2;
            
        }else if (state ==4)
        {
            _bgView.width =  RealValue_W(550);
            _bgView.height = RealValue_W(564);
            [_bgView addSubview:self.QcancelButton];
            [_bgView addSubview:self.QimageView];
            [_bgView addSubview:self.measageLable];
            _measageLable.mj_y = _QimageView.bottom;
        }
        
    }
    self.recharBlock=block;
    return self;
}
- (void)setQrcodeUrl:(NSString *)qrcodeUrl
{
    _qrcodeUrl = qrcodeUrl;
    [_QimageView sd_setImageWithURL:[NSURL URLWithString:qrcodeUrl]];
}
- (UIView *)bgView
{
    if (!_bgView) {
        _bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, RealValue_W(600), RealValue_H(400))];
        _bgView.center = self.center;
        _bgView.backgroundColor=TABLEVIEWLCOLOR;
        _bgView.layer.cornerRadius=10.0;
        _bgView.layer.masksToBounds=YES;
        _bgView.userInteractionEnabled=YES;
        if (_state ==4)
        {
            //1.创建长按手势
            UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(imglongTapClick:)];
            
            //3.添加手势
            [_bgView addGestureRecognizer:longTap];
        }else
        {
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(gesture)];
            [_bgView addGestureRecognizer:tap];
        }
        
    }
    return _bgView;
}
- (UIImageView *)imageView
{
    if (!_imageView) {
        _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(RealValue_H(32), RealValue_H(40), RealValue_H(44), RealValue_H(44))];
        _imageView.image = [UIImage imageNamed:@"tisicon_jing"];
    }
    return _imageView;
}
- (UIView *)titleLable
{
    if (!_titleLable) {
        _titleLable = [[UILabel alloc] initWithFrame:CGRectMake(_imageView.right+RealValue_H(18), 0, _bgView.width - 40, 30)];
        _titleLable.text = _titleStr;
        _titleLable.textColor = MAINTITLECOLOR;
        _titleLable.font=AutoBoldFont(18);
        _titleLable.adjustsFontSizeToFitWidth = YES;
        _titleLable.centerY = _imageView.centerY;
    }
    return _titleLable;
}
- (UILabel *)measageLable
{
    if (!_measageLable) {
        _measageLable = [[UILabel alloc] initWithFrame:CGRectMake(RealValue_H(32),_titleLable.bottom + RealValue_H(15), _bgView.width - 40, 60)];
        _measageLable.text = _measage;
        _measageLable.textAlignment=NSTextAlignmentCenter;
        _measageLable.font=AutoFont(15);
        _measageLable.textColor = RGBA(114, 145, 161, 1);
        _measageLable.numberOfLines = 0;
        _measageLable.adjustsFontSizeToFitWidth = YES;
    }
    return _measageLable;
}
- (UIButton *)okButton
{
    if (!_okButton) {
        _okButton = [[UIButton alloc] initWithFrame:CGRectMake(_bgView.width/2, _bgView.height - RealValue_W(96), _bgView.width/2, RealValue_W(96))];
        
        [_okButton setTitle:_confirmtext forState:(UIControlStateNormal)];
        [_okButton setTitleColor:MAINTITLECOLOR1 forState:UIControlStateNormal];
        [_okButton addTarget:self action:@selector(OKclick) forControlEvents:(UIControlEventTouchUpInside)];
        _okButton.layer.masksToBounds     =YES;
        _okButton.layer.cornerRadius      =2;
        _okButton.titleLabel.font = AutoFont(15);
    }
    return _okButton;
}
- (UIButton *)cancelButton
{
    if (!_cancelButton) {
        _cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(0, _bgView.height - RealValue_W(96), _bgView.width/2, RealValue_W(96))];
        
        [_cancelButton setTitle:_canceltext forState:(UIControlStateNormal)];
        [_cancelButton setTitleColor:TABTITLECOLOR forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(cancelclick) forControlEvents:(UIControlEventTouchUpInside)];
        _cancelButton.titleLabel.font = AutoFont(15);
        
    }
    return _cancelButton;
}
- (UIImageView *)QimageView
{
    if (!_QimageView) {
        _QimageView = [[UIImageView alloc] initWithFrame:CGRectMake(_bgView.width/2 - RealValue_W(290)/2, _bgView.height/2 -RealValue_W(320)/2 , RealValue_W(290), RealValue_W(320))];
        
    }
    return _QimageView;
}
- (UIButton *)QcancelButton
{
    if (!_QcancelButton) {
        _QcancelButton = [[UIButton alloc] initWithFrame:CGRectMake(_bgView.width -  RealValue_W(100), 4, RealValue_W(80), RealValue_W(80))];
        [_QcancelButton setImage:[UIImage imageNamed:@"jion_cancel"] forState:0];
        [_QcancelButton addTarget:self action:@selector(cancelclick) forControlEvents:(UIControlEventTouchUpInside)];
        
    }
    return _QcancelButton;
}
-(void)OKclick{
    
    if (self.recharBlock)
    {
        self.recharBlock();
        
    }
    if (_state == 2)
    {
        [self dismissAlertView];
    }
    
}
- (void)gesture
{
    
}
- (void)getViewHeight
{
    _bgView.height = RealValue_H(500);
    _measageLable.textAlignment=NSTextAlignmentLeft;
    _measageLable.height = 120;
    _okButton.mj_y = _bgView.height - RealValue_W(96);
}
- (void)dismiss
{
    if (_state == 3 ||_state == 4)
    {
        [self dismissAlertView];
    }
    
}
-(void)cancelclick
{
    [self dismissAlertView];
}
#pragma mark 长按手势弹出警告视图确认
-(void)imglongTapClick:(UILongPressGestureRecognizer*)gesture
{
    
    if(gesture.state==UIGestureRecognizerStateBegan)
    {
        SC_ActionSheet *sheet = [[SC_ActionSheet alloc]initWithFirstTitle:@"" secondTitle:Localized(@"Save_Album")];
        sheet.selectedSth = ^(NSInteger tag) {
            
            
            switch (tag) {
                case 1:
                    // 保存图片到相册
                    UIImageWriteToSavedPhotosAlbum([self captureImageFromView:self.bgView],self,@selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:),nil);
                    break;
                    
                default:
                    break;
            }
            
        };
        [sheet show];
        
        
        
    }
    
}
-(UIImage *)captureImageFromView:(UIView *)view{
    
    UIGraphicsBeginImageContextWithOptions(view.frame.size,NO, 0);
    
    [[UIColor clearColor] setFill];
    
    [[UIBezierPath bezierPathWithRect:view.bounds] fill];
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    [view.layer renderInContext:ctx];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
    
}
#pragma mark 保存图片后的回调
- (void)imageSavedToPhotosAlbum:(UIImage*)image didFinishSavingWithError:  (NSError*)error contextInfo:(id)contextInfo
{
    NSString*message =@"";
    
    if(!error) {
        
        message =Localized(@"Asset_Saved_album");
        
        [EXUnit showSVProgressHUD:message];
        [self dismiss];
        
    }else
        
    {
        
        message = [error description];
        [EXUnit showMessage:Localized(@"album_message")];
        [self dismiss];
    }
    
}
-(void)dismissAlertView
{
    //     NSString *param=[NSString stringWithFormat:@"meid=%@",[WJUnit getUdid]];
    //    [self POSTWithHost:@"" path:appversion_update_choice param:@{@"sign":[WJUnit base64StringFromText:param]} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    //        if ([responseObject[@"errorNo"] integerValue]==200)
    //        {
    //
    //        }
    //
    //    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    //
    //    }];
    [self removeFromSuperview];
    
}

-(void)showLXAlertView
{
    [kWindow addSubview:self];
    [self setShowAnimation];
}
-(void)setShowAnimation{
    WeakSelf;
    switch (_animationStyle) {
            
        case LXASAnimationDefault:
        {
            [UIView animateWithDuration:0 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                [weakSelf.bgView.layer setValue:@(0) forKeyPath:@"transform.scale"];
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.23 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                    [weakSelf.bgView.layer setValue:@(1.2) forKeyPath:@"transform.scale"];
                } completion:^(BOOL finished) {
                    [UIView animateWithDuration:0.09 delay:0.02 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                        [weakSelf.bgView.layer setValue:@(.9) forKeyPath:@"transform.scale"];
                    } completion:^(BOOL finished) {
                        [UIView animateWithDuration:0.05 delay:0.02 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                            [weakSelf.bgView.layer setValue:@(1.0) forKeyPath:@"transform.scale"];
                        } completion:^(BOOL finished) {
                            weakSelf.userInteractionEnabled = YES;
                        }];
                    }];
                }];
            }];
        }
            break;
            
        case LXASAnimationLeftShake:{
            
            CGPoint startPoint = CGPointMake(-_bgView.width, self.center.y);
            weakSelf.bgView.layer.position=startPoint;
            
            //damping:阻尼，范围0-1，阻尼越接近于0，弹性效果越明显
            //velocity:弹性复位的速度
            [UIView animateWithDuration:.8 delay:0 usingSpringWithDamping:.5 initialSpringVelocity:1.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
                weakSelf.bgView.layer.position=self.center;
                
            } completion:^(BOOL finished) {
                
            }];
        }
            break;
            
        case LXASAnimationTopShake:{
            
            CGPoint startPoint = CGPointMake(self.center.x, -_bgView.frame.size.height);
            _bgView.layer.position=startPoint;
            
            //damping:阻尼，范围0-1，阻尼越接近于0，弹性效果越明显
            //velocity:弹性复位的速度
            [UIView animateWithDuration:.8 delay:0 usingSpringWithDamping:.5 initialSpringVelocity:1.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
                weakSelf.bgView.layer.position=self.center;
                
            } completion:^(BOOL finished) {
                
            }];
        }
            break;
            
        case LXASAnimationNO:{
            
        }
            
            break;
            
        default:
            break;
    }
}
@end
